import React, { Component } from "react";
import { connect } from "react-redux";
import lodash from "lodash";

// 组件
import MainLayout from "@component/mainLayout/mainLayout";
import Button from "@component/button/index";

import { Toast, InputItem } from "antd-mobile";

import yhTools from "@tools/yh";
import "./wallet.scss";
import { InterfaceG, agreements_url } from "@config/Config";
import Banner from "@/views/viewCommon/Banner";
import arrorwRight from "@images/paytool_right_icon.png";
import {
	setCouponListAction,
	setCouponAction
} from "@redux/Action/wallet/wallet";
import PaySkeleton from "@/component/skeleton/pay";
import XhfPaying from "@component/XhfPaying";
/**
 * 描述：
 * 作者：zenghq
 * 日期：2020-10-22
 */
@connect(
	state => ({
		selectedCoupon: state.walletReducer.selectedCoupon,
		mobile: state.getAppPlatformsDatas.mobile,
		userId: state.getAppPlatformsDatas.userId,
		extJsonStr: state.getAppPlatformsDatas.extJsonStr
	}),
	dispatch => ({
		setCouponListAction: value => dispatch(setCouponListAction(value)),
		setCouponAction: value => dispatch(setCouponAction(value))
	})
)
class wallet extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isSmsPay: true, // 是否是短信支付
			isSmsCount: false, // 是否倒计时
			countDownTime: 60, // 倒计时时间
			isSetPwd: true, // 是否设置支付密码
			preOrderData: {
				transAmount: "--",
				quotaAmount: "--"
			}, // 预下单信息
			password: "", // 支付密码
			smsCode: "", // 短信验证码
			isClickedSend: true, // 是否点击过发送验证码
			status: "-1",
			bannerList: [],
			isPopup: false
		};
		this.verifyToken = ""; // 短信验证码token
	}
	/*******************生命周期 start************************/
	async componentDidMount() {
		Toast.info(XhfPaying(), 100);
		let isSetPwd = await this.checkSetPassword();
		if (isSetPwd) {
			this.setState({
				isSetPwd,
				isSmsPay: false
			});
		} else {
			this.setState({
				isSetPwd,
				isSmsPay: true
			});
		}
		let resPreOrder = await this.preOrder();
		const { code, data, message = "" } = resPreOrder;
		if (code === "0") {
			this.setState({
				preOrderData: data,
				status: 1
			});
			const { couponBoList = [] } = data;
			this.props.setCouponListAction(couponBoList);
			this.props.setCouponAction(couponBoList[0]);
			Toast.hide();
		} else {
			const { query = {} } = this.props.location;
			if (query.payScene == "SPAY") {
				// 彩食鲜
				Toast.info(
					message,
					2,
					() => {
						this.props.history.goBack();
					},
					true
				);
				return;
			} else {
				// 通知生活支付结果
				yhTools.noticePayFailed(message);
			}
		}
		this.getWalletBanner();
		// this.checkUpdateAgreement();
	}
	// componentWillUnmount = () => {};
	/*******************生命周期 end************************/

	/*******************业务方法 start************************/
	//获取banner
	async getWalletBanner() {
		let objs = {
			url: InterfaceG.walletBanner,
			params: {
				typeCode: "8"
			},
			_alertShow: false
		};
		let res = await yhTools.request(objs);
		if (res.code == "0") {
			this.setState({
				bannerList: res.data && res.data.length > 0 ? res.data : []
			});
		}
	}
	/** 检查是否设置支付密码 */
	async checkSetPassword() {
		let objs = {
			url: InterfaceG.checkSetPassword,
			params: {},
			_alertShow: false
		};
		let res = await yhTools.request(objs);
		if (res.code === "0") {
			return true;
		} else {
			return false;
		}
	}
	/**短信倒计时 */
	countDown() {
		let { countDownTime } = this.state;
		this.setState({
			isSmsCount: true,
			isClickedSend: false
		});
		this.sendTimer = setInterval(() => {
			if (countDownTime < 1) {
				clearInterval(this.sendTimer);
				this.sendTimer = null;
				this.setState({
					countDownTime: 60,
					isSmsCount: false
				});
			} else {
				countDownTime--;
				this.setState({
					countDownTime
				});
			}
		}, 1000);
	}

	/**短信支付发送短信 */
	sendVerifyCode() {
		const { preOrderData } = this.state;
		const objs = {
			url: InterfaceG.paySendVerifyCode,
			params: {
				mobilePhone: this.props.mobile,
				scene: preOrderData.outTradeNo
			}
		};
		return yhTools.request(objs);
	}

	/**预下单 */
	preOrder() {
		const { query = {} } = this.props.location;
		const objs = {
			url: InterfaceG.mmoney_pay_online_shenghuo_prepay_credit,
			params: {
				payScene: query.payScene,
				channel: "03"
			}
		};
		return yhTools.request(objs);
	}
	/**确认支付 */
	confirmPay() {
		const { selectedCoupon = {} } = this.props;
		const { preOrderData, password, smsCode, isSmsPay } = this.state;
		if (!preOrderData) {
			// 通知生活支付结果
			yhTools.noticePayFailed("预下单失败，请重新发起");
			return;
		}
		if (isSmsPay && !this.checkSmsCode(smsCode)) {
			// 验证码登录校验失败
			return;
		}
		if (!isSmsPay && !this.checkPassword(password)) {
			// 密码登录校验失败
			return;
		}
		const objs = {
			url: InterfaceG.mmoney_password_confirm,
			params: {
				couponNo: selectedCoupon.no || "",
				outTradeNo: preOrderData.outTradeNo,
				tradeNo: preOrderData.tradeNo,
				verifyToken: this.verifyToken,
				password,
				smsCode,
				verifyType: isSmsPay ? "1" : "2", // 验密方式(1验证码(类型为验证码时smsCode不能为空) /2密码(类型为密码时password不能为空))
				payTool: "1001" // 小辉付
			}
		};
		const { query = {} } = this.props.location;
		const { successUrl, failUrl } = query;
		Toast.info(XhfPaying(), 100);
		yhTools.request(objs).then(res => {
			const { code, data, message = "" } = res;
			if (code === "0") {
				if (successUrl) {
					// 有成功页就去成功页
					this.props.history.push({
						pathname: successUrl,
						query: {
							payResult: data
						}
					});
					// 通知生活支付结果
					yhTools.noticePaySuccess("支付成功", false);
				} else {
					// 通知生活支付结果
					yhTools.noticePaySuccess("支付成功");
				}
			} else if (code === "11006") {
				Toast.info(message, 2);
			} else if (failUrl) {
				// 有成功页就去成功页
				this.props.history.push({
					pathname: failUrl,
					query: {
						payResult: res
					}
				});
				// 通知生活支付结果
				yhTools.noticePayFailed(message, false);
			} else {
				// 通知生活支付结果
				yhTools.noticePayFailed(message);
			}
		});
	}
	/**检测密码正确性 */
	checkPassword(password) {
		if (!password) {
			Toast.info("密码不能为空", 2);
			return false;
		}
		if (password.length != 6) {
			Toast.info("请输入六位支付密码", 2);
			return false;
		}
		return true;
	}
	/**检测验证码正确性 */
	checkSmsCode(smsCode) {
		const { isClickedSend } = this.state;

		if (isClickedSend) {
			Toast.info("请先获取短信验证码", 2);
			return false;
		}
		if (!smsCode) {
			Toast.info("验证码不能为空", 2);
			return false;
		}
		return true;
	}
	/**动态获取输入类型 */
	getInputType() {
		if (yhTools.platform() == "android") {
			return "number";
		}
		if (yhTools.platform() == "ios") {
			return "tel";
		}
	}
	/**取消支付 */
	cancelOrder() {
		yhTools.noticePayCanceled("取消支付");
	}
	/*******************业务方法 end************************/

	/*******************点击事件 start************************/
	/**切换支付方式 */
	changePaytoolClick() {
		let { isSmsPay } = this.state;
		this.setState({
			isSmsPay: !isSmsPay
		});
	}
	/**点击确认支付 */
	confirmPayClick() {
		if (this.state.isPopup) {
			yhTools.debounceNew(this.updateAgreement(), 200);
		} else {
			yhTools.debounceNew(this.confirmPay(), 200);
		}
	}
	//检查是否需要更新循环合同
	checkUpdateAgreement() {
		let objs = {
			url: InterfaceG.updateAgreement,
			params: {
				source: "02" //01:首页合同更新弹窗，02:支付确认合同弹窗
			},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				//isPopup 0:不弹  1:弹
				if (res.data.isPopup == "1") {
					this.setState({
						isPopup: true
					});
				} else {
					this.setState({
						isPopup: false
					});
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	handleGoHetong() {
		this.props.history.push({
			pathname: "/iframeAgreements",
			state: {
				src: agreements_url + "/xhfCreditPaymentContract.html",
				title: "个人循环授信借款合同"
			}
		});
	}
	//同意签署新的合同
	agreeNewAgreement = () => {
		let objs = {
			url: InterfaceG.agreeNewAgreement,
			params: {},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				this.confirmPay();
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	/**点击发送验证码 */
	async sendVerifyCodeClick() {
		const { mobile } = this.props;
		const { isSmsCount } = this.state;
		if (!mobile) {
			Toast.info("获取手机号失败", 2);
			return;
		}
		if (isSmsCount) {
			return;
		}
		let res = await this.sendVerifyCode();
		const { code, data } = res;
		if (code === "0") {
			this.verifyToken = data.verifyToken;
			this.countDown(60);
			Toast.info(
				`已向您手机${mobile.slice(0, 3)}****${mobile.slice(7, 11)}发送验证码`
			);
		} else {
			Toast.info(res.message, 2);
		}
	}
	/**密码输入改变 */
	inputChange(e) {
		let value = e.target.value;
		if (e.target.value.length > 6) {
			value = e.target.value.slice(0, 6);
		}
		this.setState(
			{
				password: value
			},
			() => {
				if (value.length === 6) {
					document.activeElement.blur();
				}
			}
		);
	}
	/**点击选券 */
	selectCouponClick() {
		this.props.history.push("/selectCouponForH5");
	}
	/**验证码输入 */
	smsCodeChange(v) {
		if (v && v.length === 6) {
			document.activeElement.blur();
		}
		this.setState({
			smsCode: v
		});
	}
	/*******************点击事件 end************************/

	/**渲染 */
	render() {
		const {
			isSetPwd,
			isSmsPay,
			isSmsCount,
			countDownTime,
			preOrderData,
			password,
			isClickedSend,
			status,
			bannerList
		} = this.state;
		const { selectedCoupon } = this.props;
		const _pageParams = {
			header: {
				title: "支付确认",
				// goToApp: true,
				goBackAction: () => {
					const { query = {} } = this.props.location;
					if (query.payScene == "SPAY") {
						// 彩食鲜
						this.props.history.goBack();
					} else {
						this.cancelOrder();
					}
				}
			},
			componentDidRecover: () => {
				// 缓存
				//当从合同页返回时，弹起合同更新弹窗
				let toSee = sessionStorage.getItem("toSeeAgreement");
				if (toSee && toSee == "01") {
					this.openModalArlart();
					sessionStorage.removeItem("toSeeAgreement");
				}
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};
		return (
			<MainLayout pageParams={_pageParams}>
				<PaySkeleton load={status === "-1"}>
					<div className="wallet-box">
						{/* 头部 */}
						<section className="wallet-top_content">
							<p className="shop-name">订单金额</p>
							<p className="unit">
								¥<span className="pay-money">{preOrderData.transAmount}</span>
							</p>
						</section>
						{/* 详情 */}
						<section className="wallet-detail_content">
							<div className="wallet-detail-item">
								<div className="item-left">小辉付可用额度</div>
								<div className="item-right">¥{preOrderData.quotaAmount}</div>
							</div>

							<div className="wallet-detail-item">
								<div className="item-left">支付优惠</div>
								{selectedCoupon ? (
									<div
										onClick={this.selectCouponClick.bind(this)}
										className="item-right red"
									>
										<div className="money">-¥{selectedCoupon.couponValue}</div>
										<img src={arrorwRight} className="arrorw-img" />
									</div>
								) : (
									<div className="item-right">暂无</div>
								)}
							</div>
							<div
								className="wallet-detail-item"
								style={{ borderBottomWidth: "0px" }}
							>
								<div className="item-left">支付活动</div>
								<div className="item-right red">随机减最高99元</div>
							</div>

							<div className="wallet-detail-item paytool-box">
								<div className="item-left">
									{!isSmsPay ? "密码支付" : "验证码支付"}
									{isSetPwd && (
										<span
											className="change-input"
											onClick={this.changePaytoolClick.bind(this)}
										>
											｜ 切换
											{isSmsPay ? "密码支付" : "验证码支付"}
										</span>
									)}
								</div>
							</div>
						</section>

						{!isSmsPay && (
							<section className="wallet-input-box">
								<div className="wallet-pwd_input-box">
									<input
										className="pwd-input"
										value={password}
										type={this.getInputType()}
										pattern="[0-9]"
										maxLength={6}
										onChange={e => {
											this.inputChange(e);
										}}
									/>
									{["", "", "", "", "", ""].map((item, index) => {
										return password && password.split("")[index] ? (
											<div key={index} className="input-item">
												.
											</div>
										) : (
											<div key={index} className="input-item"></div>
										);
									})}
								</div>
							</section>
						)}
						{isSmsPay && (
							<section className="wallet-input-box">
								<div className="wallet-sms_input-box">
									<InputItem
										clear
										placeholder="请输入验证码"
										maxLength={6}
										minLength={6}
										pattern="[0-9]{6}"
										type="tel"
										className="sms-input"
										onChange={this.smsCodeChange.bind(this)}
										extra={
											<div
												className={isSmsCount ? "send-code send" : "send-code"}
											>
												{isClickedSend
													? "发送"
													: isSmsCount
													? `重发${countDownTime}s`
													: "重发"}
											</div>
										}
										onExtraClick={lodash.throttle(
											this.sendVerifyCodeClick.bind(this),
											2000,
											{ trailing: false }
										)}
									></InputItem>
								</div>
							</section>
						)}
						{this.state.isPopup && (
							<p
								style={{
									textAlign: "center",
									color: "#888888",
									fontSize: "0.24rem",
									marginTop: "0.24rem"
								}}
							>
								点击按钮，表示您已阅读并同意
								<span
									style={{ color: "#302E2F", fontSize: "0.24rem" }}
									onClick={() => this.handleGoHetong()}
								>
									《个人循环信用额度贷款合同》
								</span>
							</p>
						)}
						<Button
							style={{
								marginTop: "0.24rem",
								marginBottom: "0.7rem"
							}}
							onClick={this.confirmPayClick.bind(this)}
							buttonStyle={{
								height: "1rem",
								lineHeight: "1rem",
								borderRadius: "0.5rem"
							}}
						>
							确认支付
						</Button>
						{bannerList && bannerList.length > 0 && (
							<Banner bannerList={bannerList} history={this.props.history} />
						)}
						{/* //<div className="wallet_guide"></div> */}
					</div>
				</PaySkeleton>
			</MainLayout>
		);
	}
}

export default wallet;
